import { numberFormat } from '@/utils'
import Song from '@/entity/Song'
import { detail, url } from 'api/song'


class PlayList {
  constructor(
    {
      id,
      playCount,
      name,
      coverImgUrl,
      picUrl,
      description,
      creator,
      shareCount,
      commentCount,
      tags,
      highQuality,
      subscribedCount,
      subscribed,
      subscribers,
      trackCount,
      trackIds = [],// 歌曲清单
      privileges = [],  // vip歌曲
      userId
    },
  )
  {
    this.id = id // id
    this.name = name // 歌单名称
    this.description = description // 描述
    this.coverImgUrl = coverImgUrl // 封面图
    this.picUrl = picUrl || coverImgUrl
    this.playCount = numberFormat(playCount) // 播放数量
    this.creator = creator // 创建人
    this.shareCount = shareCount // 分享数
    this.commentCount = numberFormat(commentCount) // 评论数
    this.tags = tags // 标签
    this.highQuality = highQuality // 是否是精品歌单
    this.subscribedCount = numberFormat(subscribedCount) // 收藏数
    this._subscribedCount = subscribedCount // 为转换
    this.subscribed = subscribed // 是否收藏
    this.subscribers = subscribers // 最新收藏人数
    this.trackCount = numberFormat(trackCount) // 歌曲总数
    this.userId = userId // 创建歌单用户id

    this.privileges = privileges.map(item => item.id)
    // this.trackIds = trackIds.map(item => item.id).join(',')
    this.trackIds = trackIds
  }
  getSongList({ pageSize = 100, pageNum = 1 }) {
    return new Promise((resolve, reject) => {
      let start = pageNum === 1 ? 0 : pageSize * (pageNum - 1)
      let end = pageSize * pageNum
      let ids = this.trackIds.slice(start, end).map(item => item.id).join(',')

      if (ids === '') {
        resolve([])
        return 
      }

      Promise.all([detail(ids), url(ids)]).then(res => {
        let songList = res[0].songs
        let urlList = res[1].data
        
        songList = songList.map(song => {
          let _song = new Song(song)
          // _song.isVip = this.privileges.includes(song.id)
          let url = urlList.find(url => url.id === song.id)
          _song.url = url.url
          _song.percentage = 0 // 下载进度
          return _song
        }).filter(song => song.url)

        // songList = songList.map((song, index) => {
        //   let _song = new Song(song)
        //   _song.isVip = this.privileges.includes(song.id)
        //   _song.url = urlList[index].url
        //   _song.percentage = 0 // 下载进度
        //   return _song
        // })
        resolve(songList)
      }).catch(err => {
        reject(err)
      })
    })
  }

  updateSubscribedCount(type = 'add') {
    type === 'add' ? this._subscribedCount++ : this._subscribedCount--
    this.subscribedCount = numberFormat(this._subscribedCount)
  }
}

export default PlayList